package attr

import (
	"context"
	"mall/common/excption"
	constans "mall/services/product/rpc/consts"
	"mall/services/product/rpc/internal/domain/bo"
	"mall/services/product/rpc/internal/mapper"
	"mall/services/product/rpc/internal/mapper/entity"
	"time"

	"mall/services/product/rpc/internal/svc"
	"mall/services/product/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type SaveAttrValueLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSaveAttrValueLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SaveAttrValueLogic {
	return &SaveAttrValueLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SaveAttrValueLogic) SaveAttrValue(in *pb.SaveAttrValueDTO) (*pb.SaveAttrValueVO, error) {
	// 1.check request dto
	valueMapper, checkErr := l.checkRequestDTO(in)
	if checkErr != nil {
		return nil, checkErr
	}
	// 2.save db
	idArr, err := l.saveDB(in, valueMapper)
	if err != nil {
		return nil, err
	}
	// 3.return obj
	return &pb.SaveAttrValueVO{AttrValueId: idArr}, nil
}

func (l *SaveAttrValueLogic) saveDB(in *pb.SaveAttrValueDTO, valueMapper *mapper.AttrValueMapper) ([]int64, error) {
	valueArr := in.Value
	now := time.Now()
	var attrValueArr []*entity.AttrValueEntity
	for _, v := range valueArr {
		valueEntity := new(entity.AttrValueEntity)
		valueEntity.AttrId = in.GetAttrId()
		valueEntity.Value = v
		valueEntity.UpdateTime = now
		valueEntity.CreateTime = now
		attrValueArr = append(attrValueArr, valueEntity)
	}
	saveErr := valueMapper.BatchInsertCtx(l.svcCtx.DBEngin, attrValueArr)
	if saveErr != nil {
		return nil, saveErr
	}
	var idArr []int64
	for _, v := range attrValueArr {
		idArr = append(idArr, v.AttrValueId)
	}
	return idArr, nil
}

func (l *SaveAttrValueLogic) checkRequestDTO(in *pb.SaveAttrValueDTO) (*mapper.AttrValueMapper, error) {
	attrMapper := mapper.NewAttrMapper(l.ctx)
	attrBO := bo.AttrBO{
		AttrId: in.AttrId,
	}
	selectCountCtx, err := attrMapper.SelectCountCtx(l.svcCtx.DBEngin, attrBO)
	if err != nil {
		return nil, err
	}
	if selectCountCtx <= 0 {
		return nil, excption.NewErrCode(constans.AttrNotExistErr)
	}
	valueMapper := mapper.NewAttrValueMapper(l.ctx)
	valueBO := bo.AttrValueBO{AttrId: in.AttrId, ValueArr: in.Value}
	countCtx, err := valueMapper.SelectCountCtx(l.svcCtx.DBEngin, valueBO)
	if err != nil {
		return nil, err
	}
	if int(countCtx) > 0 {
		return nil, excption.NewErrCode(constans.AttrValueRepeatErr)
	}
	return valueMapper, nil
}
